package win.devhu.testing.simple.jsoupdemo

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import org.jsoup.Jsoup
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL


//获取zealdocs下载地址
fun main(args: Array<String>){
    val docsetsURL = "http://api.zealdocs.org/v1/docsets"
    val baseDurl = "http://tokyo.kapeli.com/feeds/"
    val doc = Jsoup.connect(docsetsURL).ignoreContentType(true).execute()  //请求JSON
    val jsonArry = JSON.parseArray(doc.body())
    for (json  in jsonArry){
        val jsonObj = json as JSONObject
        val name = jsonObj["name"]
        val Durl = baseDurl + name + ".tgz"
        var size = getFileSize(Durl).toDouble()/1024/1024   //获取文件大小，单位为M
        println("$name \t $Durl \t ${String.format("%.2f",size)} M") //保留两位输出
    }
    println("总共份${jsonArry.size -1}文档")
}

//通过URL获取下载文件大小,注意获取到的文件大小为字节，如果需要转1M = 1024*1024 B
private fun getFileSize(url: String): Int {

    var url = URL(url)
    try {
        var conn = url.openConnection()
        (conn as HttpURLConnection).setRequestMethod("HEAD")
        conn.getInputStream()
        return conn.getContentLength()
    } catch (e: IOException) {
        throw RuntimeException(e)
    }
}
